<?php
class UserModule
{
	public function login()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','user_login');

		$cache_args = array(

		);

		$cache_file = getTplCache('page/user_login',$cache_args);
		if(!@include($cache_file))
			include template('page/user_login');

		display($cache_file);
	}

	public function loginHandle()
	{
		global $_FANWE;

		$form_hash = $_FANWE['request']['form_hash'];

		//if($form_hash != FORM_HASH)
			//exit('Access Denied');

		$user['email'] = $_FANWE['request']['email'];
		$user['user_pwd'] = $_FANWE['request']['user_pwd'];
		$user['group_type'] = "User";

		$vservice = S('Validate');
		$validate = array(
			array('email','required',lang('user','user_require')),
			array('user_pwd','required',lang('user','password_require')),
		);

		if($vservice->validation($validate,$user))
		{
			$service = S('User');

			if($vservice->email($user['email']))
				$user['email'] = DB::resultFirst('SELECT user_name FROM '.DB::table('user')." WHERE email = '$user[email]'");

			$code = $_FANWE['setting']['integrate_code'];
			if (empty($code))
				$code = 'fanwe';

			$is_login = false;

			if($code != 'fanwe')
			{
				$users = &init_users();
				$is_login = $users->login($user['email'],$user['user_pwd']);
				if($is_login)
					fSetCookie('ucdata', authcode($_COOKIE['ucdata'], 'ENCODE'), 31536000);
			}

			$user['user_pwd'] = md5($user['user_pwd']);
			$user_info = $service->getUserByNamePwd($user['email'],$user['user_pwd']);

			if($user_info)
			{
				$cookie_time = isset($_FANWE['request']['cookie_time']) ? intval($_FANWE['request']['cookie_time']) : 0;
				$service->setSession($user_info,$cookie_time);
				$service->updateUserScore($user_info['id'],"User","Login");
				DB::update('user',array('last_time'=>getTodayTime(),'last_ip'=>$_FANWE['client_ip']),'id = '.$user_info['id']);
				fHeader("location: ".U('index/index'));
			}
			else
			{
				$error = lang('user','login_error');
				include template('page/user_login');
				display();
			}
		}
		else
		{
			$error = $vservice->getError();
			include template('page/user_login');
			display();
		}
	}

	public function reg()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','user_reg');

		$cache_args = array(

		);

		$cache_file = getTplCache('page/user_reg',$cache_args);
		if(!@include($cache_file))
			include template('page/user_reg');

		display($cache_file);
	}

	public function regHandle()
	{
		global $_FANWE;

		$form_hash = $_FANWE['request']['form_hash'];

		//if($form_hash != FORM_HASH)
			//exit('Access Denied');

		$user = array(
			'email'            => $_FANWE['request']['email'],
			'user_name'        => $_FANWE['request']['user_name'],
			'user_pwd'         => $_FANWE['request']['user_pwd'],
			'user_pwd_confirm' => $_FANWE['request']['user_pwd_confirm'],
			'city_id'          => intval($_FANWE['request']['city_id']),
		);

		$vservice = S('Validate');
		$validate = array(
			array('email','required',lang('user','register_email_require')),
			array('email','email',lang('user','register_email_error')),
			array('user_name','required',lang('user','register_user_name_require')),
			array('user_name','range_length',lang('user','register_user_name_range'),3,15),
			array('user_pwd','required',lang('user','register_password_require')),
			array('user_pwd_confirm','equal',lang('user','confirm_password_error'),$user['user_pwd']),
		);

		if($vservice->validation($validate,$user))
		{
			$is_login = false;

			$service = S('User');

			$code = $_FANWE['setting']['integrate_code'];
			if (empty($code))
				$code = 'fanwe';

			if($code != 'fanwe')
			{
				$users = &init_users();
				$is_add = $users->add_user($user['user_name'],$user['user_pwd'],$user['email']);
				if(!$is_add)
					$error = lang('user',$users->error);
				else
				{
					$uc_arr = $users->get_profile_by_name($user['user_name']);
					$user['ucenter_id'] = $uc_arr['id'];
				}
			}
			else
			{
				if($service->getEmailExists($user['email']))
					$error = lang('user','register_email_exist');

				if($service->getUserNameExists($user['user_name']))
					$error = lang('user','register_user_name_exist');
			}

			if(empty($error))
			{
				$user_pwd = $user['user_pwd'];
				$user['user_pwd'] = md5($user['user_pwd']);
				unset($user['user_pwd_confirm']);
				$user['parent_id'] = $service->getReferrals();
				$user['group_type'] = 'User';
				$user['group_id'] = 1;
				$user['status'] = 1;
				$user['create_time'] = TIME_UTC;
				$user['update_time'] = TIME_UTC;

				$uid = DB::insert('user',$user,true);

				if($uid > 0)
				{
					$user['id'] = $uid;
					$service->updateUserScore($uid,"User","Register");
					$service->referralHandle($uid,$user['parent_id'],$user['user_name']);
					$service->setSession($user);
					if($code != 'fanwe')
					{
						$is_login = $users->login($user['user_name'],$user_pwd);
						if($is_login)
							fSetCookie('ucdata', authcode($_COOKIE['ucdata'], 'ENCODE'), 31536000);
					}

					fHeader("location: ".U('index/index'));
				}
				else
					$error = lang('user','register_error');
			}
		}
		else
			$error = $vservice->getError();

		if(!empty($error))
		{
			include template('page/user_reg');
			display();
		}
	}

	public function getPwd()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','user_getpwd');
		include template('page/user_getpwd');
		display();
	}

	public function sendPwd()
	{
		global $_FANWE;

		$data = array(
			'email'            => $_FANWE['request']['email'],
		);

		$vservice = S('Validate');
		$validate = array(
			array('email','required','注册邮箱不能为空'),
			array('email','email','邮箱格式错误'),
		);

		if(!$vservice->validation($validate,$data))
			exit;

		$code = $_FANWE['setting']['integrate_code'];
		if (empty($code))
			$code = 'fanwe';

		if($code != 'fanwe')
		{
			$users = &init_users();
			$is_reg = $users->check_email($data['email']);
		}
		else
			$is_reg = S('User')->getEmailExists($data['email']);

		if(!$is_reg)
		{
			$error = '该帐号不存在';
			include template('page/user_getpwd');
			display();
		}
		else
		{
			include import('class/mail');
			$mail = new Mail();

			$user_name = DB::resultFirst('SELECT user_name FROM '.DB::table('user')."
							WHERE email = '$data[email]'");

			if(empty($user_name))
				$user_name = $data['email'];

			$pwd = random(8);
			$title = "重设密码－－".$_FANWE['setting']['site_name'];
			$msg = "hi $user_name,<br><br>\r\n您在 ".$_FANWE['setting']['site_name']." 申请了重设密码，现已将你的密码重置为".$pwd."，请登陆网站更改为你熟悉的密码：<br><br><br>\r\n<a href=\"".SITE_URL.U('user/login')."\" target=\"_blank\">".SITE_URL.U('user/login')."</a><br><br>\r\n-- <br>\r\n".$_FANWE['setting']['site_name'];

			if($mail->send($data['email'],$data['email'],$title,$content,1))
			{
				DB::update('UPDATE '.DB::table('user')." SET user_pwd = '".md5($pwd)."' WHERE email = '$data[email]'");
				showSuccess('操作提示','发送重设密码邮件到'.$data['email'].'成功',U('user/login'));
			}
			else
			{
				$error = current($mail->getError());
				include template('page/user_getpwd');
				display();
			}
		}
	}

	public function logout()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','user_logout');

		$code = $_FANWE['setting']['integrate_code'];
		if (empty($code))
			$code = 'fanwe';

		if($code != 'fanwe')
		{
			$users = &init_users();
			$is_login = $users->logout();
			fSetCookie('ucdata', authcode($_COOKIE['ucdata'], 'ENCODE'), 31536000);
		}

		S('User')->clearSession();
		fHeader("location: ".U('index/index'));
	}

	public function center()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','user_center');

		$cache_args = array(

		);

		$cache_file = getTplCache('page/user_center',$cache_args);
		if(!@include($cache_file))
			include template('page/user_center');

		display($cache_file);
	}

	public function top()
	{
		$cache_file = getTplCache('user/top');
		if(!@include($cache_file))
			include template('user/top');
		display($cache_file);
	}

	public function menu()
	{
		global $_FANWE;
		$cache_file = getTplCache('user/menu');
		if(!@include($cache_file))
			include template('user/menu');
		display($cache_file);
	}

	public function modify()
	{
		global $_FANWE;

		$user = S('User')->getUserById($_FANWE['user']['id']);
		$user['data'] = unserialize($user['data']);
		$user['score'] = S('User')->getUserScore($_FANWE['user']['id'],$_FANWE['user']['ucenter_id']);
		include template('user/modify');
		display();
	}

	public function modifyHandle()
	{
		global $_FANWE;

		$user['city_id'] = intval($_FANWE['request']['city_id']);
		$user['tel'] = trim($_FANWE['request']['tel']);
		$user['qq_msn'] = trim($_FANWE['request']['qq_msn']);
		$user['update_time'] = gmtTime();
		$data['email'] = trim($_FANWE['request']['data']['email']);
		$user['data'] = serialize($data);

		DB::update('user',$user,'id = '.$_FANWE['user']['id']);

		fHeader("location: ".U('user/modify'));
		exit;
	}

	public function password()
	{
		global $_FANWE;
		include template('user/password');
		display();
	}

	public function repwd()
	{
		global $_FANWE;

		$user = S('User')->getUserById($_FANWE['user']['id']);

		if(md5($_FANWE['request']['yuan_pwd']) == $user['user_pwd'])
		{
			$code = $_FANWE['setting']['integrate_code'];
			if (empty($code))
				$code = 'fanwe';

			if($code != 'fanwe')
			{
				$users = &init_users();
				$uc['email'] = '';
				$uc['username'] = $user['user_name'];
				$uc['password'] = $_FANWE['request']['user_pwd'];
				$users->edit_user($uc);
			}

			$user['user_pwd'] = md5($_FANWE['request']['user_pwd']);
			$user['update_time'] = TIME_UTC;
			$success = '修改密码成功';

			DB::update('user',array('user_pwd'=>$user['user_pwd']),'id = '.$_FANWE['user']['id']);

			S('User')->setSession($user);
		}
		else
		{
			$error = '原密码不正确，请重新输入';
		}

		include template('user/password');
		display();
	}

	public function order()
	{
		global $_FANWE;

		$args = array();
		$where = " AND user_id = ".$_FANWE['user']['id'];
		$goods_status = intval($_FANWE['request']['status']);
		if($goods_status > 0)
		{
			$where.=" AND goods_status = ".($goods_status - 1);
			$args['status'] = $goods_status;
		}
		else
		{
			$goods_status = 0;
		}

		$count = DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('order').' WHERE status < 2 '.$where);
		$pager = buildPage('user/order',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);

		$sql = 'SELECT * FROM '.DB::table('order').' WHERE status < 2 '.$where.' GROUP BY id ORDER BY id DESC LIMIT '.$pager['limit'];

		$res = DB::query($sql);
		$list = array();
		while($order = DB::fetch($res))
		{
			$order['goods_status'] = lang('user','order_goods_status_'.$order['goods_status']);
			$order['create_time'] = toDate($order['create_time']);
			$list[] = $order;
		}

    	include template('user/orderlist');
		display();
    }

	public function collect()
	{
		global $_FANWE;
		$delete = !isset($_POST['delete']) ? 0 : intval($_POST['delete']);
		if($delete == 1)
		{
			$ids = $_FANWE['request']['ids'];

			if(is_array($ids) && count($ids) > 0)
			{
				$ids = implode(',',$ids);
				DB::delete('user_goods','user_id = '.$_FANWE['uid'].' AND id IN ('.$ids.')');
			}
		}

		$time = TIME_UTC;

		$args = array();

		$order = $_FANWE['request']['order'];

		$orders = array(
			'end_time' => 'g.end_time ASC',
			'bought' => 'g.bought DESC',
			'price' => 'price ASC',
			'discount' => 'discount DESC'
		);

		$sort = $orders['end_time'];

		$type = $_FANWE['request']['type'];

		$types = array('unexpired','expired');

		if(empty($type) || !in_array($type,$types))
			$type = '';
		else
			$args['type'] = $type;

		if(empty($order) || !array_key_exists($order,$orders))
			$order = '';
		else
		{
			$args['order'] = $order;
			$sort = $orders[$order];
		}

		$where = '';

		switch($type)
		{
			case 'unexpired':
				$where .= " AND end_time > $time";
			break;

			case 'expired':
				$where .= " AND end_time <= $time";
			break;
		}

		$count = DB::resultFirst('SELECT COUNT(ug.id) FROM '.DB::table('user_goods').' as ug
				INNER JOIN '.DB::table('goods').' AS g ON g.id = ug.goods_id AND g.status = 1
				WHERE ug.user_id = '.$_FANWE['uid'].$where);

		$pager = buildPage('user/collect',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);
		$query = DB::query('SELECT ug.*,g.name AS goods_name,g.site_id,g.small_img,g.end_time,g.shop_price AS price,g.market_price,(g.shop_price / g.market_price) AS discount,g.site_name,g.bought FROM '.DB::table('user_goods').' AS ug
							INNER JOIN '.DB::table('goods').' AS g ON g.id = ug.goods_id AND g.status = 1
							WHERE ug.user_id = '.$_FANWE['uid'].$where.' ORDER BY '.$sort.' LIMIT '.$pager['limit']);

		$list = array();

		while($goods = DB::fetch($query))
		{
			if($goods['end_time'] < TIME_UTC)
				$goods['is_end'] = 1;

			S('Goods')->goodsFormat($goods);

			$list[] = $goods;
		}

		include template('user/collectlist');
		display();
    }

	public function custom()
	{
		global $_FANWE;
		$delete = !isset($_POST['delete']) ? 0 : intval($_POST['delete']);
		if($delete == 1)
		{
			$ids = $_FANWE['request']['ids'];

			if(is_array($ids) && count($ids) > 0)
			{
				$ids = implode(',',$ids);
				DB::delete('user_site','user_id = '.$_FANWE['uid'].' AND site_id IN ('.$ids.')');
			}
		}


		$args = array();

		$count = DB::resultFirst('SELECT COUNT(us.site_id) FROM '.DB::table('user_site').' as us
				INNER JOIN '.DB::table('site').' AS s ON s.id = us.site_id AND s.status = 1 AND s.id > 0
				WHERE us.user_id = '.$_FANWE['uid']);

		$pager = buildPage('user/custom',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);
		$query = DB::query('SELECT s.name,s.id FROM '.DB::table('user_site').' as us
				INNER JOIN '.DB::table('site').' AS s ON s.id = us.site_id AND s.status = 1 AND s.id > 0
				WHERE us.user_id = '.$_FANWE['uid'].' LIMIT '.$pager['limit']);

		$list = array();

		while($site = DB::fetch($query))
		{
			$site['url'] = U("site/show",array("id"=>$site['id']));
			$list[] = $site;
		}

		include template('user/customlist');
		display();
    }

	public function score()
	{
		global $_FANWE;

		$args = array();

		$count = DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('user_score_log').' WHERE user_id = '.$_FANWE['uid']);

		$pager = buildPage('user/score',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);
		$query = DB::query('SELECT * FROM '.DB::table('user_score_log').' WHERE user_id = '.$_FANWE['uid'].' ORDER BY id DESC LIMIT '.$pager['limit']);

		$list = array();

		while($log = DB::fetch($query))
		{
			$log['create_time'] = toDate($log['create_time']);
			$list[] = $log;
		}

		include template('user/scorelist');
		display();
    }

	public function referral()
	{
		global $_FANWE;

		$args = array();

		$where = " r.is_pay = 1 and r.parent_id = ".$_FANWE['uid'];

		$count = DB::resultFirst('SELECT COUNT(r.id) FROM '.DB::table('referrals').' as r WHERE '.$where);

		$pager = buildPage('user/referral',$args,$count,$_FANWE['page'],$_FANWE['setting']['page_listrows']);

		$query = DB::query('SELECT r.*,u.user_name FROM '.DB::table('referrals').' AS r
				INNER JOIN '.DB::table('user').' AS u ON u.id = r.user_id
				WHERE '.$where.' ORDER BY r.id DESC LIMIT '.$pager['limit']);

		$list = array();

		while($data = DB::fetch($query))
		{
			$data['create_time'] = toDate($data['create_time']);
			$data['pay_time'] = toDate($data['pay_time']);
			$list[] = $data;
		}

		include template('user/referrallist');
		display();
    }
}
?>